var sequenceModel = require('../models/sequence'),
    apiHandler = require('../services/api-handler'),
    crypto = require('crypto'),
    fs = require('fs'),
    json2csv = require('json2csv');

exports.createSequence = function (req, res) {
    var bodyParams = req.body,
        newSequence = {};
    newSequence.pageName = bodyParams.sequence.pageName;
    newSequence.timeSpent = bodyParams.sequence.timeSpent;
    newSequence.user = req.user._id;
    var sequence = new sequenceModel(newSequence);
    sequenceModel.createSequence(sequence, apiHandler.handler.check(res, 'NO_SEQUENCE', function (seq) {
        apiHandler.setSuccessResponse(seq, res);
    }));
};

exports.getUserSequence = function (req, res) {
    sequenceModel.getUserSequence(req.body, apiHandler.handler.check(res, 'NO_SEQUENCE', function (seq) {
        apiHandler.setSuccessResponse(seq, res);
    }));
};

exports.getSequenceCSV = function (req, res) {
    sequenceModel.getUserSequenceCSV(req.body, apiHandler.handler.check(res, 'NO_SEQUENCE', function (seq) {
        var arrayCSV = seq;
        crypto.randomBytes(10, function (err, buffer) {
            var token = buffer.toString('hex');
            var filePath = process.env.CSV_UPLOAD_DEST + token + '.csv';
            var fields = ['_id', 'updatedAt', 'createdAt', 'user', 'pageName', 'timeSpent', 'name'];
            try {
                var result = json2csv({data: arrayCSV, fields: fields});
                fs.writeFile(filePath, result, function (err) {
                    if (err) {
                        return console.log(err);
                    }
                    apiHandler.setSuccessResponse(filePath, res);
                });
            } catch (err) {
                console.log(err);
                apiHandler.setErrorResponse('CSV_ERROR', res);
            }
        });
    }));
};

exports.getAllUsersSequence = function (req, res) {
    sequenceModel.getAllUsersSequence(apiHandler.handler.check(res, 'NO_SEQUENCE', function (seq) {
        apiHandler.setSuccessResponse(seq, res);
    }));
};
